import 'package:flutter/material.dart';
import 'network/api_client.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Encryption Test',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: TestPage(),
    );
  }
}

class TestPage extends StatefulWidget {
  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  final _apiClient = ApiClient();
  String _result = '';
  bool _isLoading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Encryption Test')),
      body: Padding(
        padding: EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ElevatedButton(
              onPressed: _isLoading ? null : _testLogin,
              child: _isLoading 
                  ? Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CircularProgressIndicator(strokeWidth: 2),
                        SizedBox(width: 10),
                        Text('Testing...'),
                      ],
                    )
                  : Text('Test Encrypted Login'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _isLoading ? null : _testPing,
              child: Text('Test Ping (No Encryption)'),
            ),
            SizedBox(height: 20),
            Expanded(
              child: Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(5),
                ),
                child: SingleChildScrollView(
                  child: Text(
                    _result.isEmpty ? 'Click a button to test...' : _result,
                    style: TextStyle(fontFamily: 'monospace'),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _testLogin() async {
    setState(() {
      _isLoading = true;
      _result = 'Testing encrypted login...\n\n';
    });

    try {
      final response = await _apiClient.login('admin', 'password');
      
      setState(() {
        _result += '✅ Login Success!\n\n';
        _result += 'Response Type: ${response.runtimeType}\n';
        _result += 'Response Data:\n';
        _result += _formatMap(response, 0);
        
        // 测试具体字段访问
        if (response['success'] != null) {
          _result += '\n🔍 Field Access Test:\n';
          _result += 'Success: ${response['success']}\n';
          _result += 'Message: ${response['message']}\n';
          
          if (response['data'] != null) {
            final data = response['data'];
            _result += 'Data Type: ${data.runtimeType}\n';
            if (data is Map<String, dynamic>) {
              _result += 'Token: ${data['token']}\n';
              _result += 'User Info: ${data['user_info']}\n';
            }
          }
        }
      });
    } catch (e) {
      setState(() {
        _result += '❌ Login Failed!\n\n';
        _result += 'Error: $e\n';
        _result += 'Error Type: ${e.runtimeType}\n';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _testPing() async {
    setState(() {
      _isLoading = true;
      _result = 'Testing ping (no encryption)...\n\n';
    });

    try {
      final response = await _apiClient.ping();
      
      setState(() {
        _result += '✅ Ping Success!\n\n';
        _result += 'Response Type: ${response.runtimeType}\n';
        _result += 'Response Data:\n';
        _result += _formatMap(response, 0);
      });
    } catch (e) {
      setState(() {
        _result += '❌ Ping Failed!\n\n';
        _result += 'Error: $e\n';
        _result += 'Error Type: ${e.runtimeType}\n';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  String _formatMap(Map<String, dynamic> map, int indent) {
    String result = '';
    final prefix = '  ' * indent;
    
    map.forEach((key, value) {
      if (value is Map<String, dynamic>) {
        result += '$prefix$key:\n';
        result += _formatMap(value, indent + 1);
      } else {
        result += '$prefix$key: $value\n';
      }
    });
    
    return result;
  }
}
